<?php

declare (strict_types = 1);

namespace own\exception;

use own\helps\RespCode;
use own\helps\OwnLogger;
use think\Exception;
use think\facade\Db;
use think\Response;

class TransException
{
    /**
     * @param string $class 类名
     * @param string $method 执行方法
     * @param ...$argc 参数
     */
    public static function exec($class, $method, ...$argc): Response
    {
        Db::startTrans();
        try {
            $result = call_user_func_array([make($class), $method], $argc);
            Db::commit();
            return self::respData($result, '请求成功', RespCode::SUCCESS);
        } catch (TipsException $e) {
            Db::rollback();
            return self::respData('', $e->getMessage(), RespCode::ERROR);
        } catch (Exception $e) {
            Db::rollback();
            OwnLogger::debug($e->getMessage(), $argc ? json_encode($argc) : '');
            return self::respData('', env('APP_DEBUG') ? $e->getMessage() : RespCode::DEF_TIPS, RespCode::ERROR);
        }
    }
    /**
     * response
     */
    public static function respData($data, $message, $code): Response
    {
        return json(['code' => $code, 'message' => $message, 'data' => $data]);
    }
    
}
